package u.hnx.admin.security.core;

import cn.hutool.core.util.ObjectUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.access.intercept.RequestAuthorizationContext;
import org.springframework.stereotype.Component;
import u.hnx.admin.security.api.AuthorManager;

import java.util.Arrays;
import java.util.function.Supplier;
@Component
@EnableConfigurationProperties(SecurityProperties.class)
public record AuthorizationManagerCustomizer(SecurityProperties securityProperties,AuthorManager authorManager) implements AuthorizationManager<RequestAuthorizationContext> {
    @Override
    public AuthorizationDecision check(Supplier<Authentication> authentication, RequestAuthorizationContext requestAuthorizationContext) {
        HttpServletRequest request = requestAuthorizationContext.getRequest();
        String url = request.getRequestURI().replace(request.getContextPath(), "");
        if (ObjectUtil.isNotEmpty(securityProperties.getOpenApi()) &&
        securityProperties.getOpenApi().length>0 && Arrays.stream(securityProperties.getOpenApi()).anyMatch(n -> n.equalsIgnoreCase(url))) {
            return new AuthorizationDecision(true);
        }
        return authorManager.check(authentication,url);
    }
}
